<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon class="relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div class="absolute top-4px right-10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #toolbar>
        <Dropdown
          :trigger="['click']"
          :dropMenuList="[
            {
              text: '创建新的租户配置',
              icon: ICON.ADDENTITY,
              event: '',
              onClick: () => {
                openAddModal(true, { key: 'add' });
              },
            },
          ]"
        >
          <a-button type="primary">添加租户配置</a-button>
        </Dropdown>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :stopButtonPropagation="true"
            :actions="[
              {
                icon: ICON.EDIT,
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: ICON.CHECK,
                tooltip: {
                  title: '查看',
                  placement: 'top',
                },
                onClick: handleDetail.bind(null, record),
              },
              {
                icon: ICON.DELETE,
                onClick: handleDelete.bind(null, record),
                disabled: record.default,
              },
            ]"
            :dropDownActions="[
              {
                icon: ICON.DOWNLOAD,
                label: '导出租户配置',
                onClick: handleDownload.bind(null, record),
              },
              {
                icon: ICON.FLAG,
                label: '设置该租户配置为默认',
                onClick: handleSetDefault.bind(null, record),
                disabled: record.default,
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <AddModal @register="registerAddModal" @success="handleSuccess" />
    <PublicDrawer
      @register="registerDrawer"
      :show-tabs="['detail', 'attribute', 'telemetry', 'alarm']"
    />
  </div>
</template>

<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { Alert, Tooltip } from 'ant-design-vue';
  import { tableSchema, searchSchema, detailSchema } from './index.data';
  import { tableStyleSetting, tableFormStyleSetting } from '/@/settings/thingsBoardDesign';
  import { Dropdown } from '/@/components/Dropdown';
  import {
    getTableList,
    download,
    setDefault,
  } from '/@/api/thingsborad/profile/tenantProfile/tenantProfile';
  import { TableParams } from '/@/api/thingsborad/profile/tenantProfile/model/tenantProfileModel';
  import { saveAs } from 'file-saver';
  import Icon from '/@/components/Icon';
  import { ICON } from '/@/enums/iconEnum';
  import { useMessage } from '/@/hooks/web/useMessage';
  import AddModal from './components/AddModal/AddModal.vue';
  import { useModal } from '/@/components/Modal';
  import {
    addNewProfiles,
    deleteProfiles,
    getInfoById,
  } from '/@/api/thingsborad/profile/tenantProfile/tenantProfile';
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';
  import { useDrawer } from '/@/components/Drawer';
  import { ref } from 'vue';

  const checkedKeys = ref<any>([]);
  const { createConfirm } = useMessage();
  const [registerAddModal, { openModal: openAddModal, closeModal: closeAddModal }] = useModal();
  const [registerDrawer, { openDrawer }] = useDrawer();

  const [registerTable, { reload, setProps }] = useTable({
    title: '租户配置',
    columns: tableSchema,
    ...tableStyleSetting,
    api: getTableList,
    beforeFetch: (value) => {
      let params: TableParams = {
        page: 0,
        pageSize: 10,
        sortProperty: value.field ? value.field : 'createdTime',
        sortOrder: value.order == 'ascend' ? 'ASC' : 'DESC',
        textSearch: value.textSearch,
      };
      return params;
    },
    afterFetch: (res) => {
      let list: Array<object> = [];
      res.length != 0
        ? res.forEach((item) => {
            list.push({
              id: item.id.id,
              createdTime: item.createdTime,
              name: item.name,
              remark: item.description,
              default: item.default,
              record: item,
            });
          })
        : null;
      return list;
    },
    formConfig: {
      layout: 'horizontal',
      schemas: searchSchema,
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 8 },
        lg: { span: 6, offset: 12 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },
    fetchSetting: {
      pageField: 'page',
      sizeField: 'pageSize',
      listField: 'data',
      totalField: 'totalElements',
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
      getCheckboxProps: (record) => {
        return {
          disabled: record.default,
        };
      },
    },
  });

  // 编辑
  function handleEdit(record: Recordable) {
    openAddModal(true, { key: 'edit', record: record.record });
  }
  // 详情
  function handleDetail(record: Recordable) {
    openDrawer(true, {
      entityType: ENTITY_TYPE.TENANT_PROFILE,
      entityId: record.id,
      title: record.name,
      api: getInfoById,
      detailSchema: detailSchema,
      params: record.id,
    });
  }
  // 删除
  function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要删除租户配置 '${record.name}'吗？`,
      content: '请注意：确认后，租户配置和所有相关数据将不可恢复。',
      onOk: async () => {
        await deleteProfiles(record.id);
        reload();
      },
    });
  }
  // 导出
  async function handleDownload(record: Recordable) {
    const res = await download(record.id);
    const jsonBlob = new Blob([JSON.stringify(res)], {
      type: 'application/json',
    });
    saveAs(jsonBlob, `${record.name}.json`);
  }
  // 设为默认
  function handleSetDefault(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要将租户配置 '${record.name}' 设为默认值吗？`,
      content: '确认后，此租户配置将被标记为默认配置，并将用于未指定配置的新租户。',
      onOk: async () => {
        let params = {
          profileId: record.id,
          payload: {
            headers: {
              normalizedNames: {},
              lazyUpdate: null,
            },
            params: {
              updates: null,
              cloneFrom: null,
              encoder: {},
              map: null,
              interceptorConfig: {
                ignoreLoading: false,
                ignoreErrors: false,
                resendRequest: false,
              },
            },
          },
        };
        await setDefault(params);
        reload();
      },
    });
  }
  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected: boolean, _selectedRows: Recordable[], changeRows: Recordable[]) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  // 多选删除
  function handleSelectedDelete() {
    createConfirm({
      iconType: 'info',
      title: `确定要删除${checkedKeys.value.length}个租户配置吗？`,
      content: '请注意：确认后，所有选定的租户配置将被删除，所有相关数据将不可恢复。',
      onOk: async () => {
        setProps({ loading: true });
        for (const item of checkedKeys.value) {
          await deleteProfiles(item);
        }
        reload();
        checkedKeys.value = [];
      },
    });
  }
  async function handleSuccess(key: string, params: Recordable) {
    if (!params.isolatedTbRuleEngine) {
      params.profileData.queueConfiguration = null;
    }
    switch (key) {
      case 'add':
        await addNewProfiles(params);
        closeAddModal();
        reload({ sortInfo: { field: 'createdTime', order: 'DESC' } });
        break;
    }
  }
</script>
